//
//  DetailReplyCell.swift
//  MM2
//
//  Created by 李成明 on 2022/1/11.
//

import UIKit
import ActiveLabel

class DetailReplyCell: UITableViewCell {
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var model: DailyReplyModel? {
        didSet {
            updateUI()
        }
    }
    
    private var nameClickClosure: ((Int) -> Void)?
    
    private var contentLabel: ActiveLabel = {
        let view = ActiveLabel()
        view.numberOfLines = 0
        view.font = .systemFont(ofSize: 14)
        view.hashtagColor = .initWithRGB(97, 167, 247)
        return view
    }()
    
    private var bottomLine: UIView = {
        let view = UIView()
        view.backgroundColor = mainColor
        view.alpha = 0.3
        return view
    }()
}

extension DetailReplyCell {
    private func setupUI() {
        contentView.addsubViews([contentLabel, bottomLine])
        
        contentLabel.snp.makeConstraints { make in
            make.left.equalTo(contentView).offset(16)
            make.right.equalTo(contentView).offset(-16)
            make.top.equalTo(contentView).offset(8)
            make.bottom.equalTo(contentView).offset(-8)
            make.height.equalTo(20)
        }
        
        bottomLine.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(contentView)
            make.height.equalTo(0.3)
        }
        
        contentLabel.handleHashtagTap { [weak self] str in
            self?.userNameClickAction(name: str)
        }
    }
    
    private func updateUI() {
        guard let model = model else { return }
        
        let centerStr = (model.touserId != 0) ? " 回复 #\(model.touserName)" : ""
        contentLabel.text = "#\(model.userName)" + centerStr + ": \(model.content)"
        let size = contentLabel.sizeThatFits(CGSize(width: kScreenWidth - 32, height: CGFloat.greatestFiniteMagnitude))
        
        contentLabel.snp.updateConstraints { make in
            make.height.equalTo(size.height)
        }
    }
    
    private func userNameClickAction(name: String) {
        guard let model = model else { return }
        let userID = (name == model.userName ? model.userId : (name == model.touserName ? model.touserId : -1))
        if userID != -1 {
            nameClickClosure?(userID)
        }
    }
    
    @discardableResult
    func nameClick(_ closure: @escaping ((Int) -> Void)) -> DetailReplyCell {
        nameClickClosure = closure
        return self
    }
}
